const express = require('express');
var multer = require('multer');
const path = require("path")
const app = express();

const { listBuckets, list, deleteObject, put } = require("./bin")

// 设置存储配置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/'); // 文件上传后保存的目录
    },
    filename: function (req, file, cb) {
        var originalname = Buffer.from(file.originalname, "latin1").toString("utf8");
        cb(null, originalname); // 自定义文件名
    }
});
// 初始化上传
const upload = multer({ storage: storage });


app.use(express.json()); // 用于解析application/json
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));



const OSS = require('ali-oss');
const client = new OSS({
    // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    accessKeyId: 'LTAI5tMZaTKp3tkiCoZWaqzN',
    accessKeySecret: 'mpn9Y3TGWorEI1ZbvusP8fkotmUUy9',
    region: 'oss-cn-beijing', // 服务时的地域 
    authorizationV4: true,
    // yourBucketName填写Bucket名称。
    bucket: 'cww-bucket',
});

app.get('/oss/picture', function (req, res) {
    listBuckets(client).then(event => {
        res.send(event.buckets);
    })
});

app.get('/oss/list', function (req, res) {
    // 处理POST请求的数据
    list(client).then(event => {
        res.send(event.objects);
    })

});

app.get('/oss/delete', function (req, res) {
    // 处理POST请求的数据
    deleteObject(client).then(event => {
        res.send(event);
    })

});

// 获取查询参数测试
app.get('/oss/search', function (req, res) {
    const query = req.query.id; // 获取查询参数q的值
    res.send(`Search results for: ${query}`);
})

// 获取路由参数
app.get('/oss/:id', (req, res) => {
    const userId = req.params.id; // 获取路由参数id的值
    res.send(`User ID: ${userId}`);
});

//   获取请求体参数
app.post('/oss/data', (req, res) => {
    const data = req.body; // 获取请求体中的数据
    console.log('data---->', data);
    res.send(`Received data: ${JSON.stringify(data)}`);
});

app.post('/oss/put', upload.single('file'), function (req, res) {
    const file = req.file;
    if (!file) {
        return res.status(400).send('No file uploaded.');
    }
    put(client,file.filename).then(result=>{
      res.send({
        fileName: result.name,
        filePath: result.url,
        size: result.size,
        code:200
    });
    })
   
})

app.listen(3010, function () {
    console.log('app is running at port 3010.');
});